using System;
using System.Collections.Generic;
using System.Text;

namespace Weazel.Microblaze.Elf
{
  public class ElfStringTable : ElfFormatEntity
  {
    private ElfSectionHeader sectionHeader;
    private byte[] rawData;

    public byte[] RawData
    {
      get { return rawData; }
      
    }

    public ElfStringTable(ElfSectionHeader section)
      : base(section.ElfFile)
    {
      this.sectionHeader = section;

      if (section.Sh_type != ElfSectionHeader.Sh_Type.SHT_STRTAB)
        throw new ElfReaderException("Section is not a string table");
    }

    public String GetString(uint index)
    {
      // todo: implement some validity checks 

      StringBuilder str = new StringBuilder();
      for (uint i = index; rawData[i] != '\0'; i++)
        str.Append((char)rawData[i]);

      return str.ToString();
    }

    public void Read()
    {
      // store old position
      long position = ElfFile.Reader.BaseStream.Position;

      // set file position
      ElfFile.Reader.BaseStream.Seek(sectionHeader.Sh_offset, 0);

      // read the raw data
      this.rawData = ElfFile.Reader.ReadBytes((int)sectionHeader.Sh_size);

      // restore position
      ElfFile.Reader.BaseStream.Seek(position, 0);
    }
  }
}
